#include "planets.h"
#include <algorithm>
#include <fstream>

Planet::Planet(const std::string &name, double mass, double radius)
    : name_(name), mass_(mass), radius_(radius) {}

const std::string &Planet::getName() const
{
    return name_;
}

double Planet::getMass() const
{
    return mass_;
}

double Planet::getRadius() const
{
    return radius_;
}

std::ostream &operator<<(std::ostream &out, const Planet &planet)
{
    out << "Name: " << planet.name_ << std::endl;
    out << "Mass: " << planet.mass_ << " kg" << std::endl;
    out << "Radius: " << planet.radius_ << " km" << std::endl
        << std::endl;
    return out;
}

std::istream &operator>>(std::istream &in, Planet &planet)
{
    in >> planet.name_ >> planet.mass_ >> planet.radius_;
    return in;
}

void PlanetSystem::addPlanet(const Planet &planet)
{
    planets_.push_back(planet);
}

void PlanetSystem::sortPlanetsByMass()
{
    std::sort(planets_.begin(), planets_.end(), [](const Planet &a, const Planet &b)
              { return a.getMass() < b.getMass(); });
}

void PlanetSystem::sortPlanetsByRadius()
{
    std::sort(planets_.begin(), planets_.end(), [](const Planet &a, const Planet &b)
              { return a.getRadius() < b.getRadius(); });
}

void PlanetSystem::printPlanets() const
{
    for (const Planet &planet : planets_)
    {
        std::cout << "Planet: " << planet.getName() << std::endl;
        std::cout << planet;
    }
}

void PlanetSystem::readPlanetsFromFile(const std::string &filename)
{
    planets_.clear();
    std::ifstream file(filename);

    if (!file)
    {
        std::cerr << "Error: Unable to open file " << filename << std::endl;
        return;
    }

    Planet planet;
    while (file >> planet)
    {
        planets_.push_back(planet);
    }

    file.close();
}

void PlanetSystem::writePlanetsToFile(const std::string &filename) const
{
    std::ofstream file(filename);

    if (!file)
    {
        std::cerr << "Error: Unable to open file " << filename << " for writing." << std::endl;
        return;
    }

    for (const Planet &planet : planets_)
    {
        file << planet << std::endl;
    }

    file.close();
}